package course.dao.impl;

import course.dao.BaseDao;
import course.dao.StuSubDao;
import course.pojo.entity.StuSub;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/1 9:47
 */
public class StuSubDaoImpl extends BaseDao<StuSub> implements StuSubDao {
    @Override
    public int addStuSub(StuSub stuSub, Connection connection) {
        String sql = "insert into t_stu_sub values(?,?);";
        return update(connection, sql, stuSub.getSid(), stuSub.getSuid());
    }


    @Override
    public List<StuSub> getList(Connection connection) {
        String sql = "select * from t_stu_sub;";
        return getBeanList(connection, sql);
    }

    @Override
    public List<StuSub> getBySid(Integer sid, Connection connection) {
        String sql = "select * from t_stu_sub where sid = ?;";
        return getBeanList(connection, sql, sid);
    }

    @Override
    public List<StuSub> getBySuid(Integer suid, Connection connection) {
        String sql = "select * from t_stu_sub where suid = ?;";
        return getBeanList(connection, sql, suid);
    }

    @Override
    public StuSub getBySidAndSuid(Integer sid, Integer suid, Connection connection) {
        String sql = "select * from t_stu_sub where sid = ? and suid = ?;";
        return getOneBean(connection, sql, sid, suid);
    }

    @Override
    public int deleteBySidAndSuid(Integer sid, Integer suid, Connection connection) {
        String sql = "delete from t_stu_sub where sid = ? and suid = ?;";
        return update(connection, sql, sid, suid);
    }

    /**
     * 批量退课
     */
    @Override
    public int deleteSelect(List<Integer> ids, Integer sid, Connection connection) {
        String sql = "delete from t_stu_sub where suid in(?) and sid = " + sid;

        String sqlIN = ids.stream()
                .map(x -> String.valueOf(x))
                .collect(Collectors.joining(",", "(", ")"));

        sql = sql.replace("(?)", sqlIN);

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            return preparedStatement.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
